var favVue = new Vue({
	el: "body",
	data: {
		favList: []
	},
	created: function() {
		init();
		_this = this;
		verifyLogin(_this); //验证用户是否登录
	},
	methods: {
		addCart: function(a) {
			favAddCart(a)
		},
		deleteFav: function(b) {
			var pid = _this.favList[b].attributes.pid
			removeCart(pid)
			_this.favList.splice(b, 1) //从vue实例中删除
		}
	}
})

function loadFav(a) {
	var username = currentUser.attributes.username
	var query = new AV.Query('Fav');
	query.equalTo("username", username);
	query.find().then(function(products) {
		for(var i = 0; i < products.length; i++) {
			var favId = products[i].attributes.pid
			searchFavItem(favId, a)
		}
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function verifyLogin(t) {
	currentUser = AV.User.current();
	if(currentUser) {
		loadFav(t)
	} else {
		location.href = "../login/login.html?RetUrl=" + getPageUrl()
	}
}

function searchFavItem(a, b) {
	var query = new AV.Query('Product');
	query.equalTo("pid", a);
	query.find().then(function(products) {
		b.favList.push(products[0])
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});
}

function favAddCart(t) {
	var pid = _this.favList[t].attributes.pid //商品id
	var user = currentUser.attributes.username //当前登录用户
	var id = new AV.Query('Cart');
	id.equalTo("pid", pid);
	var username = new AV.Query('Cart');
	username.equalTo("username", user);
	//设置组合查询的条件
	var cart = AV.Query.and(id, username);
	cart.find().then(function(products) {
		if(products.length == 0) {
			addCart(user, pid)
		} else {
			var query = new AV.Query('Cart');
			query.equalTo("pid", pid);
			query.find().then(function(products) {
				console.log(products)
				var num = products[0].attributes.num //当前购物车里该商品的数量  
				var rid = products[0].id //该商品在购物车里的真实id
				console.log(rid)
				console.log(num)
				//购物车里已经添加过当前商品，只是修改数量
				var todo = AV.Object.createWithoutData('Cart', rid);
				todo.set('num', ++num);
				// 保存到云端
				todo.save();
				alert("购物车里存在数量+1")
			}).catch(function(error) {
				console.log(JSON.stringify(error));
			});
		}
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});

}

function addCart(a, b) {
	var Product = AV.Object.extend('Cart')
	var product = new Product();
	product.set('username', a);
	product.set('pid', b);
	product.set('num', 1);
	product.save().then(function() {
		alert("添加新商品成功")
	}, function(error) {
		alert("failure")
	});
}

function removeCart(a) {
	var query = new AV.Query('Fav');
	query.equalTo("pid", a);
	query.find().then(function(products) {
		var rid = products[0].id //该商品在购物车里的真实id
		//购物车里已经添加过当前商品，只是修改数量
		var todo = AV.Object.createWithoutData('Fav', rid);
		todo.destroy().then(function(success) {
			alert("取消关注成功")// 删除成功
		}, function(error) {
			// 删除失败
		});
	}).catch(function(error) {
		console.log(JSON.stringify(error));
	});

}